package component;

import javafx.collections.ObservableList;
import javafx.scene.control.TreeItem;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import util.ProjectUtil;

import java.io.File;
import java.util.Arrays;

/**
 * 用一句话描述该文件作用
 *
 * @Author pengsamkee
 * created on 2016/11/22 22:09.
 */
public class FileTreeItem extends TreeItem<String> {

    private static final Image folderImage = new Image(ClassLoader.getSystemResourceAsStream("folder.png"));

    private static final Image excelImage = new Image(ClassLoader.getSystemResourceAsStream("page_white_excel.png"));

    private boolean notInitialized = true;

    public File getFile() {
        return file;
    }

    private File file;

    private final String[] handleFileExtensions = {"xlsx", "xls"};

    public FileTreeItem(final File file) {
        super(file.getName());
        this.file = file;
        this.setGraphic(new ImageView(file.isDirectory() ? folderImage : excelImage));
        this.setExpanded(false);
    }

    @Override
    public boolean isLeaf() {
        return !this.file.isDirectory();
    }

    @Override
    public ObservableList<TreeItem<String>> getChildren() {
        if (notInitialized) {

            notInitialized = false;

            if (this.file.isDirectory()) {
                File[] files = file.listFiles();
                ProjectUtil.sortFiles(files);

                for (File f : files) {

                    if (ProjectUtil.isExtensionFile(f, handleFileExtensions)) {
                        super.getChildren().add(new FileTreeItem(f));
                    }
                }

            }

        }

        return super.getChildren();
    }
}
